package com.xuhaijian.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuhaijian.entity.Order;
import com.xuhaijian.mapper.OrderMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
public class OrderService {
    private final OrderMapper orderMapper;

    /**
     * 保存订单（幂等处理：通过orderNo唯一索引防重复）
     * @param order 订单数据
     * @return 订单ID（失败返回-1）
     */
    @Transactional(rollbackFor = Exception.class)  // 事务控制
    public Long saveOrder(Order order) {
        // 1. 幂等校验：检查订单是否已存在
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Order::getOrderNo,order.getOrderNo());
        Order existOrder = orderMapper.selectOne(lambdaQueryWrapper);
        if (existOrder != null) {
            return existOrder.getId();  // 已存在，直接返回旧订单ID
        }
        // 2. 插入新订单
        orderMapper.insert(order);
        return order.getId();  // 返回新订单ID
    }
}